<?php

/**
 * 迭代器模式：提供了一种访问对象元素而不暴露底层表示的方法。
 * 用来遍历一个容器，并访问容器的元素。迭代器模式将算法与容器解耦，某些情况下，算法必须是特定于容器的，因此不能解耦。
 * Class Iterator
 */

class RadioStation
{
    protected $frequency;

    public function __construct(float $frequency)
    {
        $this->frequency = $frequency;
    }

    public function getFrequency(): float
    {
        return $this->frequency;
    }
}

class StationList implements Countable, Iterator
{
    /** @var array RatioStation[] */
    protected $stations = [];

    /** @var int $counter */
    protected $counter;

    public function addStation(RadioStation $station)
    {
        $this->stations[] = $station;
    }

    public function removeStation(RadioStation $toRemove)
    {
        $toRemoveFrequency = $toRemove->getFrequency();
        $this->stations = array_filter($this->stations, function(RadioStation $station) use($toRemoveFrequency) {
           return $station->getFrequency() != $toRemoveFrequency;
        });
        $this->counter--;
    }

    public function count(): int
    {
        return count($this->stations);
    }

    public function current()
    {
        return $this->stations[$this->counter];
    }

    public function key()
    {
        return $this->counter;
    }


    public function next()
    {
        $this->counter++;
        // return $this->current();
    }

    public function rewind()
    {
        $this->counter = 0;
        // return $this->current();
    }

    public function valid()
    {
        return isset($this->stations[$this->counter]);
    }
}

// usage
$stationList = new StationList();

$stationList->addStation(new RadioStation(89));
$stationList->addStation(new RadioStation(101));
$stationList->addStation(new RadioStation(122));
$stationList->addStation(new RadioStation(145.6));
$stationList->addStation(new RadioStation(186));

foreach ($stationList as $station) {
    echo $station->getFrequency() . "\n";
}

$stationList->removeStation(new RadioStation(89));

// we have met something unexpected here.
echo "---------------------------";
var_dump($stationList->key(), $stationList->rewind(), $stationList->next());
foreach ($stationList as $station) {
    echo $station->getFrequency() . "\n";
}